package com.googlecode.monitoring.web;

import com.googlecode.monitoring.model.ItemToCheck;
import com.googlecode.monitoring.webpages.dao.WebPageXmlAgentStatusDao;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Author: Sergiy Doroshenko
 * Date: Sep 3, 2010
 * Time: 3:27:06 PM
 */
public class WebPageAgentStatusBean extends StatusBean {
    private List<? extends ItemToCheck> webItems = new ArrayList<ItemToCheck>();
    Logger log = Logger.getLogger(DbAgentStatusBean.class);

    private WebPageXmlAgentStatusDao statusDao;

    protected WebPageAgentStatusBean() {
    }

    public WebPageAgentStatusBean(WebPageXmlAgentStatusDao agentStatusDao, SettingsBean settings) throws IOException {
        super(settings);
        this.statusDao = agentStatusDao;
    }

    @SuppressWarnings("unchecked")
    public List<ItemToCheck> getData() throws IOException {
        log.debug("reading webPage data");
        updateData(statusDao.getXmlWebPageStatusResource());
        webItems = statusDao.getAllItemsFromCheckReport();
        if (webItems != null) {
            setOutdatedItemsCount(calculateOutdatedItemsCount(webItems));
            Collections.sort(webItems, new Comparator<ItemToCheck>() {
                @Override
                public int compare(ItemToCheck d1, ItemToCheck d2) {
                    if (d1 != null && d2 != null && d1.getId() != null && d2.getId() != null
                            && d1.getId() != null && d2.getId() != null) {
                        return d1.getId().compareToIgnoreCase(d2.getId());
                    }
                    return 0;
                }
            });
        } else {
            log.debug("data was not found");
            dataFound = false;
        }
        return webItems == null ? Collections.EMPTY_LIST : webItems;
    }

}
